package com.yh.wcx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.yh.wcx.Constant.MyConstant;
import com.yh.wcx.entity.Student;
import com.yh.wcx.mapper.StudentMapper;
import com.yh.wcx.service.StudentSevice;
import com.yh.wcx.to.StudentTo;
import com.yh.wcx.util.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("studentService")
public class StudentServiceImpl implements StudentSevice {
    @Resource
    private StudentMapper studentMapper;

    @Override
    public R queryStudentById(Long id) {
        Student student = studentMapper.queryStudentById(id);
        if(student!=null){
            return R.ok(MyConstant.SUCESS_MESSAGE,student);
        }else{
            return R.ok(MyConstant.QUERY_MESSAGE_STUDENT);
        }
    }

    @Override
    public R updateStudent(StudentTo studentTo) {
        Student student = BeanUtil.copyProperties(studentTo, Student.class);
        int updateStudent = studentMapper.updateStudentById(student);
        if(updateStudent>0){
            return R.ok(MyConstant.SUCESS_MESSAGE);
        }else{
            return R.error(MyConstant.FAIL_MESSAGE);
        }
    }

    @Override
    public R delStudentById(Long id) {
        int delStudentById = studentMapper.delStudentById(id);
        if(delStudentById>0){
          return R.ok(MyConstant.SUCESS_MESSAGE);
        }else{
          return R.error(MyConstant.FAIL_MESSAGE);
        }
    }

    @Override
    public R insertStudent(StudentTo studentTo) {
        //将 前端传送过来的 to 进行属性 对拷
        Student student = BeanUtil.copyProperties(studentTo, Student.class);
        //进行参数校验
        if(student.getId()==null ||student.getId().equals("")){
            return R.error(MyConstant.INSERT_MESSAGE_ID);
        }
        if(student.getName()==null ||student.getName().equals("")){
            return R.error(MyConstant.INSERT_MESSAGE_NAME);
        }
        if(student.getSex()==null ||student.getSex().equals("")){
            return R.error(MyConstant.INSERT_MESSAGE_SEX);
        }
        if(student.getPhone()==null ||student.getPhone().equals("")){
            return R.error(MyConstant.INSERT_MESSAGE_PHONE);
        }
        if(student.getAddress()==null ||student.getAddress().equals("")){
            return R.error(MyConstant.INSERT_MESSAGE_ADDRESS);
        }
        Long aLong = studentMapper.insertStudent(student);
        //有可能 插入数据 数据格式错误 导致插入失败
        if(aLong>0){
            return R.ok(MyConstant.SUCESS_MESSAGE);
        }else{
            return R.error(MyConstant.INSERT_MESSAGE);
        }

    }




    /**
     *  多表查询
     * @param id  学生id
     * @return
     */
    @Override
    public Student queryStudentWithCourses(Long id) {
        return studentMapper.queryStudentWithCourses(id);
    }
}
